package com.bappi.utils;

import java.io.File;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;

public class MediaPlayerUtils {

	private static float volume = 1.0f;
	private static MediaPlayer mediaPlayerRec = null;

	public static synchronized void setVolume(float vol) {
		try {
			volume = vol;
			if (mediaPlayerRec != null) {
				mediaPlayerRec.setVolume(volume, volume);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static synchronized void stopPlaying() {
		try {
			if (mediaPlayerRec != null) {
				try {
					mediaPlayerRec.stop();
				} catch (Exception e) {
					e.printStackTrace();
				}
				mediaPlayerRec.release();
				mediaPlayerRec = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static synchronized void pause() {
		try {
			if (mediaPlayerRec != null) {
				mediaPlayerRec.pause();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static synchronized void play() {
		try {
			if (mediaPlayerRec != null) {
				mediaPlayerRec.start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static synchronized MediaPlayer playFile(Context context, File file,
			OnCompletionListener ocl) {
		// try {
		// if ((TabsController.geTextToSpeech() != null)
		// && (TabsController.geTextToSpeech().isSpeaking())) {
		// TabsController.geTextToSpeech().stop();
		// }
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		try {
			stopPlaying();
			MediaPlayer mPlayer = new MediaPlayer();
			if (ocl != null) {
				mPlayer.setOnCompletionListener(ocl);
			}
			mPlayer.setDataSource(file.getAbsolutePath());
			mPlayer.prepare();
			mPlayer.setVolume(volume, volume);
			mPlayer.start();
			mediaPlayerRec = mPlayer;
			return mPlayer;
		} catch (Exception e) {
			if (ocl != null) {
				ocl.onCompletion(null);
			}
			e.printStackTrace();
			return null;
		}
	}
}
